﻿using EnterpriseWebsiteApi.ActionResults;
using EnterpriseWebsiteApi.Dto.Product;
using EnterpriseWebsiteBLL;
using EnterpriseWebsiteEntity;
using EnterpriseWebsiteUtil.Helper;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Newtonsoft.Json;
using EnterpriseWebsiteApi.Dto;
using SqlSugar;
using EnterpriseWebsiteApi.ActionFilters;
using EnterpriseWebsiteApi.Dto.ProductPriceUnit;

namespace EnterpriseWebsiteApi.Controllers.Admin
{
    [Route("api/admin/[controller]/[action]")]
    [ApiController]
    [TypeFilter(typeof(JwtAuthorizeFilter))]
    public class ProductController : ControllerBase
    {
        private readonly ProductService _productService;
        private readonly ProductPriceCurrenciesService _productPriceCurrenciesService;
        private readonly Mapper _mapper;

        public ProductController(ProductService productService,ProductPriceCurrenciesService productPriceCurrenciesService , Mapper mapper)
        {
            _productService = productService;
            _productPriceCurrenciesService = productPriceCurrenciesService;
            _mapper = mapper;
        }

        /// <summary>
        /// 获取所有商品
        /// </summary>
        [HttpGet]
        public async Task<ActionResult> GetAll(int pageIndex = 0, int pageSize = 20, int categoryId = 0, string keyword = null)
        {
            try
            {
                TablePageDto<ProductQueryDTO> tablePageDto = new TablePageDto<ProductQueryDTO>();
                RefAsync<int> toalNumber = 0;
                var entities = await _productService.GetAllProductAsync(toalNumber, pageIndex, pageSize, categoryId, keyword);
                var dtos = _mapper.MapList<ProductQueryDTO>(entities);

                foreach (var item in dtos)
                {
                    var currenciesEntity = await _productPriceCurrenciesService.GetProductPriceCurrenciesById(item.Currencies);
                    item.CurrenciesData = _mapper.Map<ProductPriceCurrenciesDTO>(currenciesEntity);
                }

                tablePageDto.Data = dtos;
                tablePageDto.PageIndex = pageIndex;
                tablePageDto.PageSize = pageSize;
                tablePageDto.ToalNumber = toalNumber;
                return new Success(tablePageDto);
            }
            catch (Exception ex)
            {
                return new Error(ex);
            }
        }

        /// <summary>
        /// 新增商品
        /// </summary>
        /// <param name="product"></param>
        /// <returns></returns>
        [HttpPost]
        public async Task<ActionResult> Add(ProductDTO product)
        {
            try
            {
                var entity = _mapper.Map<ProductEntity>(product);
                entity.DetailImageUrls = JsonConvert.SerializeObject(product.Images);
                var newObj = await _productService.AddProductAsync(entity);
                return new Success(newObj);
            }
            catch (Exception ex)
            {
                return new Error(ex);
            }
        }

        /// <summary>
        /// 删除商品
        /// </summary>
        /// <param name="id"></param>
        /// <returns></returns>
        [HttpGet]
        public async Task<ActionResult> Delete(int id)
        {
            try
            {
                await _productService.DeleteProductById(id);
                return new Success();
            }
            catch (Exception ex)
            {
                return new Error(ex);
            }
        }

        /// <summary>
        /// 改变商品发布状态
        /// </summary>
        /// <param name="id"></param>
        /// <param name="publish"></param>
        /// <returns></returns>
        [HttpGet]
        public async Task<ActionResult> ChangePublish(int id,bool publish)
        {
            try
            {
                await _productService.ChangePublish(id, publish);
                return new Success();
            }
            catch (Exception ex)
            {
                return new Error(ex);
            }
        }

        /// <summary>
        /// 改变首页展示状态
        /// </summary>
        /// <param name="id"></param>
        /// <param name="state"></param>
        /// <returns></returns>
        [HttpGet]
        public async Task<ActionResult> ChangeHomeShow(int id, bool state)
        {
            try
            {
                await _productService.ChangeHomeShow(id, state);
                return new Success();
            }
            catch (Exception ex)
            {
                return new Error(ex);
            }
        }

        /// <summary>
        /// 根据Id获取一个商品
        /// </summary>
        /// <param name="id"></param>
        /// <returns></returns>
        [HttpGet]
        public async Task<ActionResult> GetProductSingleById(int id)
        {
            try
            {
                var entity = await _productService.GetProductSingleByIdAsync(id);
                if (entity == null)
                {
                    throw new Exception($"Id {id} 商品不存在，请检查参数后重新提交");
                }
                ProductDTO queryDTO = _mapper.Map<ProductDTO>(entity);
                queryDTO.Images = JsonConvert.DeserializeObject<string[]>(entity.DetailImageUrls);
                return new Success(queryDTO);
            }
            catch (Exception ex)
            {
                return new Error(ex);
            }
        }

        /// <summary>
        /// 更新商品
        /// </summary>
        /// <param name="product"></param>
        /// <returns></returns>
        [HttpPost]
        public async Task<ActionResult> Update(ProductDTO product)
        {
            try
            {
                var entity = await _productService.GetProductSingleByIdAsync(product.Id);
                if (entity == null)
                {
                    throw new Exception($"Id {product.Id} 商品不存在，请检查参数后重新提交");
                }

                entity = _mapper.Map(product, entity);
                entity.DetailImageUrls = JsonConvert.SerializeObject(product.Images);
                var updatedObj = await _productService.UpdateProductAsync(entity);
                return new Success(updatedObj);
            }
            catch (Exception ex)
            {
                return new Error(ex);
            }
        }
    }
}
